
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Alexander Velichkov
 */
public class Julia extends FractalPanel implements ITweakable{
    private Complex seed;
    private static int LIMIT = 20;
    private BufferedImage canvas;
    private Complex z;
    
    public Julia()
    {
        seed = new Complex(0,0);
    }
    public Julia(Complex seed)
    {
        this.seed = new Complex(seed);
    }
    public void tweakParam(Complex paramValue)
    {
        seed = new Complex(paramValue);
        regenerate();
    }

    public void init() {
        canvas = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
    }

    public void regenerate() {
        for (int x = 0; x < getWidth(); x++) {
            for (int y = 0; y < getHeight(); y++) {
                double newX = juliaX(x);
                double newY = juliaY(y);
                z = new Complex(newX, newY);
                for (int l = 0; l < LIMIT; l++) {
                    z = z.times(z);
                    z = z.plus(seed);
                    if (z.dist() > 2) {
                        Color color;
                        if(l <= LIMIT/2) {
                            color = new Color(0, 0, (int)(50 + (255.0 - 50.0) / (LIMIT/2) * l));
                        }else{
                            int val = (int)((l - LIMIT/2.0)/(LIMIT/2) * 255 );
                            color = new Color(val, val,255);
                        }
                        int fractalColor = color.getRGB();
                        canvas.setRGB(x, y, fractalColor);
                        break;
                    }
                    if (l == LIMIT - 1) {
                        canvas.setRGB(x, y, 0);
                    }
                }
            }
        }
        repaint();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (canvas != null) {
            g.drawImage(canvas, 0, 0, null);
        }
    }

    public double juliaX(double x) {
        double newX = x / getWidth() * 4;
        return newX - 2;
    }

    public double juliaY(double y) {
        double newY = y / getHeight() * 4;
        return newY - 2;
    }
}
